package com.dmall.chapter03.section04;

import com.dmall.chapter02.section09.Graph;

import java.util.ArrayList;

/**
 * 图的深度优先遍历
 * @author wx
 * @date 2020-02-23 21:42:12
 */
public class GraphDFS {

    private Graph G;
    private boolean[] visited;
    private ArrayList<Integer> pre = new ArrayList<>();
    private ArrayList<Integer> post = new ArrayList<>();

    public GraphDFS(Graph G) {
        this.G = G;
        this.visited = new boolean[G.V()];
        for (int v = 0; v < G.V(); v++) {
            if (!visited[v]) {
                dfs(v);
            }
        }
    }

    private void dfs(int v) {
        visited[v] = true;
        pre.add(v);
        for (int w : G.adj(v)) {
            if (!visited[w]) {
                dfs(w);
            }
        }
        post.add(v);
    }

    public Iterable<Integer> preOrder() {
        return pre;
    }

    public Iterable<Integer> postOrder() {
        return post;
    }

    public static void main(String[] args) {
        String filename = GraphDFS.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        GraphDFS graphDFS = new GraphDFS(g);
        System.out.println(graphDFS.preOrder());
        System.out.println(graphDFS.postOrder());
    }
}
